package com.atguigu.gulimall.seckill.schedule;

import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gulimall.seckill.entity.SeckillGoods;
import com.atguigu.gulimall.seckill.service.SeckillBizService;
import com.atguigu.gulimall.seckill.service.SeckillGoodsService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author nicc
 * @version 1.0
 * @className SeckillGoodUpTask
 * @date 2022-10-29 03:09
 *
 * 定时任务秒杀商品上架
 */
@Slf4j
@Service
public class SeckillGoodUpTask {

    @Autowired
    private SeckillGoodsService seckillGoodsService;

    @Autowired
    private SeckillBizService seckillBizService;

    @Autowired
    RedissonClient redissonClient;

    //秒 分 时 日 月 周
    @Scheduled(cron = "30 * * * * ?")//开发
    //@Scheduled(cron = "0 0 2 * * ?")//线上
    public void upGoods() {
        //发送一个消息。ACK【保证100%消费成功】
//        RLock lock = redissonClient.getLock("seckillgood-up-lock");
//        boolean tryLock = lock.tryLock();
//        if(tryLock){
//            //保证所有微服务同时启动上架的时候，只有一个人去执行即可
//            try {
//
//            }catch (Exception e){
//                upGoods();
//            }finally {
//                lock.unlock();
//            }
//        }

        log.info("上架任务锁获取成功：正在上架当天需要参与秒杀的所有商品");
        //1、去数据库查询当天需要参与秒杀的所有商品
        String formatDate = DateUtil.formatDate(new Date());
        List<SeckillGoods> goodsByDate = seckillGoodsService.getSeckillGoodsByDate(formatDate);

        //2.同步缓存
        seckillBizService.saveSeckillGoodsToCache(goodsByDate, formatDate);
    }


    //结算前一天的秒杀商品信息
}